package com.mentalhealthplatform.utils.decryptUtils.field;

import com.mentalhealthplatform.utils.decryptUtils.DecryptionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 自定义 RequestBodyAdvice，用于在数据绑定后、验证前进行解密
 */
@ControllerAdvice
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {

    @Autowired
    private DecryptFieldProcessor decryptFieldProcessor;

    /**
     * 确定哪些请求体需要进行解密
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasParameterAnnotation(DecryptFields.class);
    }

    /**
     * 在请求体被读取并转换为Java对象之前调用
     */
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
                                           Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        // 不需要在此方法中进行处理，返回原始 inputMessage
        return inputMessage;
    }

    /**
     * 在请求体被读取并转换为Java对象之后调用
     */
    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        try {
            decryptFieldProcessor.decryptFields(body);
        } catch (DecryptionException e) {
            try {
                throw new IOException("Failed to decrypt request body", e);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
        return body;
    }

    /**
     * 处理空请求体的情况
     */
    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                  Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
